from datetime import datetime
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from .models import OrderRating, OrderComplaint, OrderExtraFee,Order, OrderStatusLog

class OrderCreateSerializer(serializers.ModelSerializer):
    """创建订单序列化器"""
    passenger_id = serializers.IntegerField(required=True)
    start_address = serializers.CharField(required=True, max_length=50)
    end_address = serializers.CharField(required=True, max_length=50)
    order_amount = serializers.DecimalField(required=True, max_digits=10, decimal_places=2)
    # 新增：坐标信息
    origin = serializers.CharField(required=False, help_text="起点坐标，格式：lng,lat")
    destination = serializers.CharField(required=False, help_text="终点坐标，格式：lng,lat")

    class Meta:
        model = Order
        fields = ['passenger_id', 'start_address', 'end_address', 'order_amount', 'origin', 'destination']

    def create(self, validated_data):
        # 处理坐标信息
        origin = validated_data.pop('origin', None)
        destination = validated_data.pop('destination', None)

        if origin:
            lng, lat = origin.split(',')
            validated_data['origin_lng'] = float(lng)
            validated_data['origin_lat'] = float(lat)

        if destination:
            lng, lat = destination.split(',')
            validated_data['destination_lng'] = float(lng)
            validated_data['destination_lat'] = float(lat)

        # 生成随机订单号：DD + 年月日时分秒 + 6位随机数 + 2位校验码
        import random
        import string
        
        # 时间部分：年月日时分秒
        time_part = datetime.now().strftime('%Y%m%d%H%M%S')
        
        # 随机部分：6位随机数字和字母组合
        random_part = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
        
        # 生成订单号：DD前缀 + 时间戳 + 随机码
        order_number = f"DD{time_part}{random_part}"
        
        # 确保订单号唯一
        while Order.objects.filter(order_number=order_number).exists():
            random_part = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
            order_number = f"DD{time_part}{random_part}"
        
        # 创建订单
        order = Order.objects.create(
            order_number=order_number,
            **validated_data
        )
        
        # 创建订单状态日志（初始状态：待接单）
        OrderStatusLog.objects.create(
            order=order,
            status=0,  # 待接单
            operator_type=1,  # 乘客操作
            operator_id=validated_data['passenger_id'],
            create_time=datetime.now(),
            remark='乘客创建订单'
        )
        
        return order

class OrderUpdateSerializer(serializers.ModelSerializer):
    """修改订单序列化器"""
    class Meta:
        model = Order
        fields = ['start_address', 'end_address', 'order_amount', 'order_status', 'driver_id']

    def update(self, instance, validated_data):
        """更新订单，如果状态发生变化则记录状态日志"""
        old_status = instance.order_status
        new_status = validated_data.get('order_status', old_status)

        # 更新订单
        instance = super().update(instance, validated_data)

        # 如果状态发生变化，记录状态日志
        if old_status != new_status:
            from .models import OrderStatusLog
            from django.utils import timezone
            status_map = {
                0: '待接单', 1: '已上车', 2: '已到达', 3: '待支付',
                4: '已支付', 5: '已取消', 6: '待评价', 7: '已评价'
            }

            # 确定操作类型和操作人ID
            driver_id = validated_data.get('driver_id') or instance.driver_id
            operator_type = 2  # 司机操作
            operator_id = driver_id if driver_id else 1  # 默认司机ID为1

            OrderStatusLog.objects.create(
                order=instance,
                status=new_status,
                operator_type=operator_type,
                operator_id=operator_id,
                create_time=timezone.now(),
                remark=f'司机操作：{status_map.get(new_status, "未知状态")}'
            )

        return instance

class OrderCancelSerializer(serializers.Serializer):
    """取消订单序列化器"""
    # 乘客ID，必填
    passenger_id = serializers.IntegerField(required=True)
    # 取消原因，非必填，允许为空，最大长度为255
    reason = serializers.CharField(required=False, allow_blank=True, max_length=255)

class OrderSerializer(serializers.ModelSerializer):
    """订单详情序列化器"""
    status_text = serializers.SerializerMethodField()
    
    class Meta:
        # 指定模型为Order
        model = Order
        # 指定字段为以下列表中的字段
        fields = [
            'id', 'order_number', 'passenger_id', 'driver_id', 
            'start_address', 'end_address', 'order_status', 'status_text',
            'order_amount', 'create_time', 'start_time', 'end_time'
        ]
    
    def get_status_text(self, obj):
        # 定义一个字典，用于存储订单状态和对应的文本
        status_map = {
            0: '待接单',
            1: '已上车',
            2: '已到达',
            3: '待支付',
            4: '已支付',
            5: '已取消',
            6: '待评价',
            7: '已评价'
        }
        # 返回订单状态对应的文本，如果订单状态不在字典中，则返回'未知状态'
        return status_map.get(obj.order_status, '未知状态')

class OrderStatusLogSerializer(serializers.ModelSerializer):
    """订单状态日志序列化器"""
    status_text = serializers.SerializerMethodField()
    operator_type_text = serializers.SerializerMethodField()
    
    class Meta:
        # 指定模型为OrderStatusLog
        model = OrderStatusLog
        # 指定要显示的字段
        fields = [
            'id', 'order', 'status', 'status_text',
            'operator_type', 'operator_type_text', 
            'operator_id', 'create_time', 'remark'
        ]
    
    def get_status_text(self, obj):
        """获取订单状态文本"""
        # 定义订单状态映射
        status_map = {
            0: '待接单',
            1: '待出发',
            2: '已上车',
            3: '已到达',
            4: '待支付',
            5: '已支付',
            6: '订单取消',
            7: '待评价',
            8: '已评价'
        }
        # 返回订单状态文本，如果订单状态不在映射中，则返回'未知状态'
        return status_map.get(obj.status, '未知状态')
    
    def get_operator_type_text(self, obj):
        """获取操作者类型文本"""
        # 定义一个字典，用于存储操作者类型和对应的文本
        type_map = {
            0: '系统',
            1: '乘客',
            2: '司机'
        }
        # 返回操作者类型对应的文本，如果不存在则返回'未知类型'
        return type_map.get(obj.operator_type, '未知类型')
class OrderRatingSerializer(serializers.ModelSerializer):
    """
    订单评价序列化器，序列化和反序列化OrderRating模型的所有字段
    """
    class Meta:
        model = OrderRating
        fields = '__all__'  # 包含所有字段

class OrderComplaintSerializer(serializers.ModelSerializer):
    """
    订单投诉序列化器，序列化和反序列化OrderComplaint模型的所有字段
    """
    class Meta:
        model = OrderComplaint
        fields = '__all__'  # 包含所有字段

class OrderExtraFeeSerializer(serializers.ModelSerializer):
    """
    订单额外费用序列化器，序列化和反序列化OrderExtraFee模型的所有字段。
    当费用类型为'附加费'时，描述(description)为必填。
    """
    def validate(self, data):
        # 如果费用类型为'附加费'，则描述必须填写
        if data.get('fee_type') == '附加费' and not data.get('description'):
            raise serializers.ValidationError({'description': '费用类型为附加费时，描述不能为空'})
        return data

    class Meta:
        model = OrderExtraFee
        fields = '__all__'  # 包含所有字段
